<template>
  <BasicForm @register="registerForm"/>
</template>
<script lang="ts" name="UserForm" setup>
import {ref, useAttrs} from 'vue';
import {BasicForm, useForm} from '@/components/form/index';
import {formSchema} from '../data/role.data';
import {saveOrUpdateUser} from '../data/role.api';

const attrs = useAttrs();
//是否是更新模式
const isUpdate = ref(true);
//主键值
const rowId = ref('');
//表单配置
const [registerForm, {setProps, resetFields, setFieldsValue, validate, updateSchema}] = useForm({
  schemas: formSchema,
  showActionButtonGroup: false,
});

async function setData(data) {
  //重置表单
  await resetFields();
  isUpdate.value = !!data?.isUpdate;
  if (isUpdate.value) {
    rowId.value = data.record.userId;
  }
  // 无论新增还是编辑，都可以设置表单值
  if (typeof data.record === 'object') {
    await setFieldsValue({
      ...data.record,
    });
  }
}

/**
 * 提交事件
 */
async function handleSubmit(callback) {
  //验证表并获取表单参数
  let values = await validate();
  //提交表单
  await saveOrUpdateUser(values, isUpdate.value);
  //prettier-ignore
  callback && callback((parentEmit) => {
    //刷新列表
    parentEmit('success', {
      isUpdate: isUpdate.value,
      values: {...values, userId: rowId.value},
    })
  })
}

/**
 * 暴露给父组件调用的方法
 */
defineExpose({
  setData,
  handleSubmit,
});
</script>
